﻿using ConfExpert.Forms.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.SatinAlma.YeniYapi
{
    public partial class StokGirisKD : XForm
    {
        int YuklemeId = 0;
        public StokGirisKD(int YuklemeId)
        {
            InitializeComponent();
            this.YuklemeId = YuklemeId;
        }

        private void StokGirisKD_Load(object sender, EventArgs e)
        {

            this.Text = "Stok Girişi";

            gvArtikel.Init("GetYukleme", YuklemeId);
            gvArtikel.AddDetailGrid(gvTop, "ProductId");

            txtFaturaNo.Caption = gvArtikel.Dataset().Tables[2].Rows[0][0].ToStr();

            gvTop.InitNewRow += gvTop_InitNewRow;
            if (gvTop.Columns.Contains(gvTop.Columns["RollId"]))
                gvTop.MakeColumnsReadOnly("RollId");

            //gvTop.OptionsBehavior.Editable = gvTop.DataTable().Rows.Count == 0;
            gvTop.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            gvArtikel.SetViewCaption("Gelen Artikeller");
            gvTop.SetViewCaption("Gelen Toplar");

            gvArtikel.SetCaptions("QtyYuklenen:Yüklenen MT");

            gvTop.FormatAsNumber(1, "Qty");
            gvTop.AddSummary("Qty");
            gvTop.AddSummary();

            gvArtikel.AddColumn("Depoya Giren MT", typeof(decimal), "SUM(Child({FK}).Qty)");
            gvArtikel.AddColumn("Top Adedi", typeof(int), "Count(Child({FK}).Qty)");
            gvArtikel.AddColumn("Kalan MT", typeof(decimal), "isnull(QtyYuklenen,0) - isnull([Depoya Giren MT],0)");
            gvArtikel.AddSummary("QtyYuklenen", "Kalan MT", "Depoya Giren MT", "Top Adedi");

            gvArtikel.FormatAsNumber(1, "Kalan MT", "Depoya Giren MT", "QtyYuklenen", "Kalan MT");
            gvArtikel.FormatAsNumber(0, "Top Adedi");

            gvArtikel.MakeReadOnly();

            gvArtikel.BestFitColumns();
            gvTop.BestFitColumns();

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            this.FormClosing += StokGiris_FormClosing;
        }

        void gvTop_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            gvArtikel.SetRowCellValue(e.RowHandle, "ProductId", gvTop.GetFocusedRowCellValue("ProductId").ToInt(-1));
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvArtikel.EndEditing();
            gvTop.EndEditing();

            Dictionary<int, decimal> FA = new Dictionary<int, decimal>();
            FA.Add(0, 0.05m);
            FA.Add(30, 0.04m);
            FA.Add(100, 0.03m);
            FA.Add(1000, 0.02m);
            FA.Add(10000, 0.01m);
            FA.Add(100000, 0.005m);

            DataTable dtArtikel = gvArtikel.DataTable();
            int fark = dtArtikel.Select("[Kalan MT] > 1 or [Kalan MT] < -1").Length;
            if (fark > 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Depoya giren ile yüklenen metrajı tutmayan satırlar var. Bu farkları gidermeden kaydedemezsiniz.", "Hata", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                return;
            }

            if (XtraMessageBox.Show("Bu form, kumaşlar depoya uğramadan direkt Karbel'e geldiğinde, giriş çıkış işlemlerinin beraber yapılması için tasarlanmıştır. Bu şartlar sağlanıyor mu?", "Uyarı", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataTable dtNewRolls = gvTop.DataTable().Select("isnull(qty,0) > 0").CopyToDataTable();
                string xml = dtNewRolls.Serialize();

                DataSet ds = Session.DataManager.ExecuteDataSet("InsStokGiris", YuklemeId, xml, WhoAmI);
                DataTable dtRollAll = ds.Tables[0];
                dtRollAll.PrimaryKey = new DataColumn[] { dtRollAll.Columns["RollId"] };
                DataTable dtAyrimAll = ds.Tables[1];
                int GelisPartisiId = intParse(ds.Tables[2].Rows[0][0]);


                DataTable t0 = new DataTable("t0");
                t0.Columns.Add("RollId", typeof(int));
                t0.Columns.Add("Qty", typeof(decimal));

                foreach (DataRow dr in dtRollAll.Rows)
                    t0.Rows.Add(dr["RollId"], dr["Qty"]);

                //AppSession.MainForm.ShowMdiChildForm(typeof(StokGirisEtiket), RollsOnce, string.Empty);

                foreach (DataRow drA in dtArtikel.Rows)
                {
                    int productId = drA["ProductId"].ToInt(-1);

                    int i = 0;
                    DataRow[] drAyrim = dtAyrimAll.Select("ProductId=" + productId, "Qty");     //en küçük ayrımdan başlayarak
                    foreach (DataRow drx in drAyrim)
                    {
                        DataTable dtRoll = dtRollAll.Select("ProductId=" + productId + " and AyrimId is null").CopyToDataTable();
                        dtRoll.PrimaryKey = new DataColumn[] { dtRoll.Columns["RollId"] };

                        if ((++i) == drAyrim.Length)    //tek/son ayrımda hesap yapmaya gerek yok!
                            foreach (DataRow d in dtRoll.Rows)
                            {
                                DataRow r = dtRollAll.Rows.Find(d["RollId"].ToInt());
                                r["AlternatifId"] = drx["AlternatifId"];
                                r["AyrimId"] = drx["AyrimId"];
                                r["YuklemeLinesId"] = drx["YuklemeLinesId"];
                            }

                        else
                        {
                            decimal target = (decimal)drx["Qty"];

                            Dictionary<int, decimal> rolls = new Dictionary<int, decimal>();
                            foreach (DataRow drR in dtRoll.Rows)
                                rolls.Add((int)drR["RollId"], (decimal)drR["Qty"]);

                            List<int> ids = SubsetSum.Select(target, rolls);

                            decimal result = 0;
                            foreach (int idSelected in ids)
                                result += (decimal)dtRoll.Rows.Find(idSelected)["Qty"];

                            decimal x = 1000;
                            if (target > 0)
                                x = Math.Abs(1 - result / target);

                            decimal FAO = 0;
                            foreach (var pair in FA)
                            {
                                if (target < pair.Key)
                                    break;

                                FAO = pair.Value;
                            }

                            if (x > FAO)
                            {
                                decimal result2 = 0;
                                int latestRollId = 0;

                                foreach (DataRow drR2 in dtRoll.Select("", "Qty"))
                                {
                                    result2 += drR2["Qty"].ToDecimal(-1);
                                    latestRollId = drR2["RollId"].ToInt(-1);
                                    DataRow r = dtRollAll.Rows.Find(latestRollId);
                                    r["AlternatifId"] = drx["AlternatifId"];
                                    r["AyrimId"] = drx["AyrimId"];
                                    r["YuklemeLinesId"] = drx["YuklemeLinesId"];

                                    if (result2 >= target)
                                        break;

                                }
                                if (result2 > target)
                                {
                                    DataTable dtNewRoll = Session.DataManager.ExecuteDataTable("TopBol_KD", latestRollId, result2 - target, WhoAmI);
                                    dtRollAll.Merge(dtNewRoll);
                                }
                            }
                            else
                                foreach (int id in ids)
                                {
                                    DataRow r = dtRollAll.Rows.Find(id);
                                    r["AlternatifId"] = drx["AlternatifId"];
                                    r["AyrimId"] = drx["AyrimId"];
                                    r["YuklemeLinesId"] = drx["YuklemeLinesId"];
                                }
                        }
                    }
                }
                //TODO: top bölme bittikten sonra bir hata alınırsa, bu kayıtların düzeltilmesi gerekecek
                string updateXml = dtRollAll.DefaultView.ToTable(true, "RollId", "AyrimId", "AlternatifId", "YuklemeLinesId").Serialize();
                Session.DataManager.ExecuteNonQuery("UpdAyrimId", updateXml);

                //DevExpress.XtraEditors.XtraMessageBox.Show("Stok girişi başarıyla kaydedildi.", "Onay", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                btnKaydet.Enabled = false;
                gvArtikel.MakeReadOnly();
                gvTop.MakeReadOnly();

                ExecuteNonQuery("UpdCikisYap", YuklemeId);
                XtraMessageBox.Show("Topların Giriş/Çıkış'ı Yapıldı.");
            }
        }

        private void StokGiris_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool res = false;
            if (btnKaydet.Enabled)
                res = XtraMessageBox.Show("Formu kapatmak istediğinize emin misiniz?", "Uyarı", MessageBoxButtons.YesNo) != DialogResult.Yes;
            e.Cancel = res;
        }

    }
}